<template>
  <div class="app-container">
    <!-- 过滤 -->
    <div class="filter-container">
      <el-input v-model="listQuery.monitoringPointName" placeholder="监测点名称" style="width: 200px;" class="filter-item" />
      <el-input v-model="listQuery.monitoringPointAddress" placeholder="监测点地址" style="width: 200px;" class="filter-item" />
      <el-select v-model="listQuery.status" default-first-option placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in status" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="resetHandler">
        重置
      </el-button>
    </div>
    <div style="margin-bottom: 10px;">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="openDialog">
        添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column align="center" label="编号">
        <template slot-scope="{row}">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="检测点名称">
        <template slot-scope="{row}">
          {{ row.monitoringPointName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="检测点地址">
        <template slot-scope="{row}">
          {{ row.monitoringPointAddress }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="实时功率">
        <template slot-scope="{row}">
          {{ row.realtimePower }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="实时电压">
        <template slot-scope="{row}">
          {{ row.realtimeVoltage }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态">
        <template slot-scope="{row}">
          <el-tag size="mini" :type="row.status != 0 ? 'danger' : ''">
            {{ row.status === 0 ? '正常' : (row.status === 1 ? '功率过载' : '电压异常') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上报时间">
        <template slot-scope="{row}">
          {{ row.reportedTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注">
        <template slot-scope="{row}">
          {{ row.remark }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="{row}">
          <el-button type="primary" icon="el-icon-edit" circle @click="openDialog(row)" />
          <el-button type="danger" icon="el-icon-delete" circle @click="openConfirm(row)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />

    <!-- 对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item v-if="form.id" label="编号" :label-width="formLabelWidth">
          <el-input v-model="form.id" placeholder="编号" :disabled="true" autocomplete="off" />
        </el-form-item>
        <el-form-item label="检测点名称" :label-width="formLabelWidth" prop="monitoringPointName">
          <el-input v-model="form.monitoringPointName" placeholder="请输入检测点名称" autocomplete="off" />
        </el-form-item>
        <el-form-item label="检测点地址" :label-width="formLabelWidth" prop="monitoringPointAddress">
          <el-input v-model="form.monitoringPointAddress" placeholder="请输入检测点地址" autocomplete="off" />
        </el-form-item>
        <el-form-item label="实时功率" :label-width="formLabelWidth" prop="realtimePower">
          <el-input v-model.number="form.realtimePower" placeholder="请输入实时功率" autocomplete="off" />
        </el-form-item>
        <el-form-item label="实时电压" :label-width="formLabelWidth" prop="realtimeVoltage">
          <el-input v-model.number="form.realtimeVoltage" placeholder="请输入实时电压" autocomplete="off" />
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
          <el-select v-model="form.status" placeholder="状态">
            <el-option label="正常" :value="0" />
            <el-option label="功率过载" :value="1" />
            <el-option label="电压异常" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="上报时间" :label-width="formLabelWidth" prop="reportedTime">
          <el-date-picker v-model="form.reportedTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="上报时间" />
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { fetchList, fetchOne, save, edit, remove } from '@/api/early-warning'
export default {
  name: 'EarlyWarning',
  components: { Pagination },
  data() {
    return {
      // 功能标题
      title: '能效预警',
      tableKey: 0,
      listLoading: true,
      // 查询参数
      listQuery: {
        page: 1,
        size: 10,
        monitoringPointName: '',
        monitoringPointAddress: '',
        status: undefined
      },
      // 状态
      status: [
        {
          label: '正常',
          key: 0
        },
        {
          label: '功率过载',
          key: 1
        },
        {
          label: '电压异常',
          key: 2
        }
      ],
      // 表格数据
      list: null,
      // 总数
      total: 0,
      // 对话框显示
      dialogFormVisible: false,
      // 对话框宽度
      formLabelWidth: '120px',
      // 表单
      form: {
        id: '',
        monitoringPointName: '',
        monitoringPointAddress: '',
        realtimePower: '',
        realtimeVoltage: '',
        status: 0,
        reportedTime: '',
        remark: ''
      },
      // 对话框标题
      dialogTitle: '',
      // 校验规则
      rules: {
        monitoringPointName: [
          { required: true, message: '请输入检测点名称', trigger: 'blur' }
        ],
        monitoringPointAddress: [
          { required: true, message: '请输入监测点地址', trigger: 'blur' }
        ],
        realtimePower: [
          { required: true, message: '请输入实时功率', trigger: 'blur' },
          { type: 'number', message: '实时功率必须为数值', trigger: 'blur' }
        ],
        realtimeVoltage: [
          { required: true, message: '请输入实时电压', trigger: 'blur' },
          { type: 'number', message: '实时电压必须为数值', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /**
     * 查询
     */
    handleFilter() {
      this.getList()
    },
    /**
     * 重置
     */
    resetHandler() {
      this.listQuery = {
        page: 1,
        size: 10,
        monitoringPointName: '',
        monitoringPointAddress: '',
        status: undefined
      }
    },
    /**
     * 获取列表
     */
    getList() {
      fetchList(this.listQuery).then(resp => {
        const { data } = resp
        this.total = data.total
        this.list = data.list
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 执行操作 修改和新增
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id) { // 有 id 就是执行修改，否则执行添加
            this.editHandler()
          } else {
            this.addHandler()
          }
        } else {
          return false
        }
      })
    },
    /**
     * 开启对话框
     * @param {*} row 行数据
     */
    openDialog(row) {
      this.dialogFormVisible = true
      // 开启对话框清空表单数据
      this.form = {
        id: '',
        monitoringPointName: '',
        monitoringPointAddress: '',
        realtimePower: '',
        realtimeVoltage: '',
        status: 0,
        reportedTime: '',
        remark: ''
      }
      // 清除 rules 原因: 不清除会导致，使用同一个对话框，上一次的规则校验提示还存在
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      // 修改
      if (row.id) {
        this.dialogTitle = `修改${this.title}`
        fetchOne(row.id).then(resp => {
          this.form = resp.data
        })
      } else { // 新增
        this.dialogTitle = `添加${this.title}`
      }
    },
    /**
     * 添加
     */
    addHandler() {
      save(this.form).then(resp => {
        this.$notify({
          title: '成功',
          message: resp.msg,
          type: 'success',
          duration: 5000
        })
      }).finally(() => {
        this.dialogFormVisible = false
        this.getList()
      })
    },
    /**
     * 修改
     */
    editHandler() {
      edit(this.form).then(resp => {
        this.$notify({
          title: '成功',
          message: resp.msg,
          type: 'success',
          duration: 5000
        })
      }).finally(() => {
        this.dialogFormVisible = false
        this.getList()
      })
    },
    /**
     * 打开确认框
     * @param {*} row 行数据
     */
    openConfirm(row) {
      const id = row.id
      this.$confirm(`此操作将永久删除编号为 ${id} 的数据`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteHandler(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
     * 删除
     * @param {*} id 行数据
     */
    deleteHandler(id) {
      console.log(id)
      remove([id]).then(resp => {
        console.log(resp)
        this.$notify({
          title: '成功',
          message: resp.msg,
          type: 'success',
          duration: 5000
        })
      }).finally(() => {
        this.getList()
      })
    }
  }
}
</script>
<style scoped></style>
